var cheerio = require("cheerio");
var async = require("async");
var utils = require('../dao/utils');
var Spider = require("./spider");

var insertDB = require("./insert.db");

var spider = new Spider('http://manhua.dmzj.com/tags/riben/*PageReplace*.shtml');
var host = "http://manhua.dmzj.com";
spider.start(fun_urls,fun_pages,fun_detail);



function fun_urls(document){
    var $ = cheerio.load(document);

    var liArry = $('.tcaricature_new .tcaricature_block ul'), urls = [];

    for (var i = 0; i < liArry.length; i++) {
        var item = liArry.eq(i);
        if (item.hasClass('ad_360_item')) {
            continue;
        }
        var url = host + item.find('li').eq(0).find('a').attr('href');
        
        urls.push(url);
    }

    return urls;
}


function fun_pages(document){
    var $ = cheerio.load(document);

    var href = $('.pages a').eq(-1).attr('href').replace('.shtml', '');
    var n = href?href.split('/'):[];
    var totalPage = n[n.length - 1];

    return totalPage;//266
}

function fun_detail(url,document){

    var $ = cheerio.load(document);

    var item = $('.anim_intro .week_mend .anim-main_list table tr');

    if (item.length == 0) {
        return false;
    }

    var chapter = [];   

    var chaptersLis = $('.cartoon_online_border li');

    for (var i = 0; i < chaptersLis.length; i++) {
        var _cur = chaptersLis.eq(i);

        chapter.push({
            href: host + _cur.find('a').attr('href').replace(/(^s*)|(s*$)/g, ""),
            chapter: _cur.find('a').attr('title').replace(/(^s*)|(s*$)/g, "")
        });
    }


    // var _sChapter = chapter.join(',');
    var _title = $('.anim_title_text h1').text().replace(/(^s*)|(s*$)/g, "");


    var data = {
        "title": _title,
        "href": url,
        "img": $('.anim_intro_ptext img').attr('src'),
        "auth": item.eq(2).find('a').text().replace(/(^s*)|(s*$)/g, ""),
        "auth_href": host + item.eq(2).find('a').attr('href').replace(/(^s*)|(s*$)/g, "").replace('../','/'),
        "news": item.eq(8).find('td a').text().replace(/(^s*)|(s*$)/g, ""),
        "news_href": host + item.eq(8).find('td a').attr('href'),
        "isFinish": item.eq(4).find('td a').text().replace(/(^s*)|(s*$)/g, "") == '已完结' ? true : false,
        "updateTime": item.eq(8).find('td .update2').text().replace(/(^s*)|(s*$)/g, ""),
        "type":  item.eq(6).find('td').text().replace(/(^s*)|(s*$)/g, ""),
        "letter": utils.letter(_title),
        "info": $('.line_height_content').length>1?$('.line_height_content').eq(1).text().replace(/(^s*)|(s*$)/g, "").replace('欢迎在动漫之家观看漫画www.dmzj.com',''):$('.line_height_content').eq(0).text().replace(/(^s*)|(s*$)/g, "").replace('欢迎在动漫之家观看漫画www.dmzj.com',''),
        "domain": host,
        "isUpdate": true,
        "chapters": chapter         
    };

    insertDB(data);



}